package main

import (
	"amazegame/packet"
	"fmt"
	"math/rand"
)

func main() {
	adapter := packet.NewAdapter(packet.VariableLengthAdapterName)
	TestPack(adapter)

	adapter = packet.NewAdapter(packet.Fixed2LengthAdapterName)
	TestPack(adapter)

	adapter = packet.NewAdapter(packet.Fixed4LengthAdapterName)
	TestPack(adapter)
}

func TestPack(adapter packet.Adapter) {

	fmt.Printf("%s\n", adapter.DumpString())

	//随机数据测试
	for i := 0; i < 20; i++ {
		l := rand.Intn(40000)
		var payload = make([]byte, l)
		newPack := adapter.PackNew(payload)

		fmt.Printf("psize:%d =>header:%v\n", len(payload), len(newPack))
		size, off := adapter.UnPack(newPack)
		fmt.Printf("UnPack psize:%d off:%d\n", size, off)
	}
	//边界数据测试
	theFun := func(PackSize int) {
		tHeader := adapter.GenHeaderByLen(uint32(PackSize))
		if tHeader == nil {
			fmt.Printf("can not Gen header %d\n", PackSize)
		} else {
			fmt.Printf("GenHeaderByLen : %d => header:%v\n", PackSize, tHeader)
			orgSize, offSet := adapter.UnPack(tHeader)
			fmt.Printf("UnPack :header:%v orgSize:%d offSet:%d\n", tHeader, orgSize, offSet)
		}
	}
	theFun(packet.MaxVarByte4Size)
	theFun(packet.MaxVarByte4Size + 1)
	theFun(packet.MaxVarByte3Size)
	theFun(packet.MaxVarByte3Size + 1)
	theFun(packet.MaxVarByte2Size)
	theFun(packet.MaxVarByte2Size + 1)
	theFun(packet.MaxVarByte1Size)
	theFun(packet.MaxVarByte1Size + 1)

	s := "111111111111111111111111112"
	packageMsg := adapter.PackNew([]byte(s))
	fmt.Printf("GenHeaderByLen : %d => header:%v\n", len(s), packageMsg)
	orgSize, offSet := adapter.UnPack(packageMsg)
	fmt.Printf("UnPack :header:%v orgSize:%d offSet:%d\n payload:%s\n", packageMsg[0:offSet], orgSize, offSet, string(packageMsg[offSet:]))

	if adapter.Name() == packet.VariableLengthAdapterName {
		b := []byte{0, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A'}
		copied := adapter.PackTo(b[1:], b, false)
		fmt.Printf("PackTo : %s %d => copied:%d\n", string(b[1:]), len(b[1:]), copied)
		orgSize, offSet = adapter.UnPack(b)
		fmt.Printf("UnPack :header:%v orgSize:%d offSet:%d\n payload:%s", b[0:offSet], orgSize, offSet, string(b[offSet:]))
	}

}
